﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using AhgoraParser.Library.Libs;
using DevExpress.XtraEditors;

namespace RegexSample
{
    public partial class MainForm : XtraForm
    {
        AhgoraWebCrawler crawler;
        AhgoraWebParser parser;
        List<RegistroGridItem> itens;
        Regex expressao;
        int ano;
        int mesAtual;
        List<Mes> meses;
        public MainForm(AhgoraWebCrawler crawler)
        {
            ano = DateTime.Now.Year;
            mesAtual = DateTime.Now.Month;
            InitializeComponent();
            this.crawler = crawler;
            DiaController.CargaHoraria = new TimeSpan(8, 45, 0);
        }

        /// <summary>
        /// Preencher o combo com os ultimos 12 meses
        /// </summary>
        private void PopularMeses() 
        {
            DateTime dataAtual = DateTime.Today;
            meses = new List<Mes>();
            bindData = new BindingSource();
            comboMes.DisplayMember = "Descricao";
            comboMes.ValueMember = "Valor";
            
            for (int i = 1; i <= 12; i++)
            {
                meses.Add(new Mes() { Descricao = dataAtual.ToString("MMMM/yyyy"), Valor = dataAtual.ToString("MM-yyyy") });
                dataAtual = dataAtual.AddMonths(-1);
            }
            bindData.DataSource = meses;
            comboMes.DataSource = bindData;
        }

        /// <summary>
        /// Preencher os registros encontrados
        /// </summary>
        public void PopularRegistros() 
        {
            itens = new List<RegistroGridItem>();
            var registros = parser.GetRegistros();
            foreach(var item in registros)
            {
                itens.Add( new RegistroGridItem( item ) );
            }
            registroGridItemBindingSource.DataSource = itens;
        }

        private void comboMes_SelectedIndexChanged(object sender, EventArgs e)
        {
            var mes = meses[comboMes.SelectedIndex];
            crawler.GetHtml(mes.Valor);
            parser = new AhgoraWebParser(crawler.HtmlSite);
            PopularRegistros();
            gridView1.RefreshData();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            bindData.DataSource = new List<Mes>();
            registroGridItemBindingSource.DataSource = new List<RegistroGridItem>();
            BeginInvoke(new Action(() =>
            {
                PopularMeses();
            }));
        }
    }
}
